package com.lyrcsoft.webflux_01.reactive;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;

public class ReactiveDemo {
    public static void main(String[] args) {
        // 发布者
        SubmissionPublisher<String> publisher = new SubmissionPublisher<String>();
        // 订阅者
        Flow.Subscriber<String> subscriber = new Flow.Subscriber<String>() {
            // 将关系那出来，后续可能需要用到
            Flow.Subscription subscription;

            @Override
            public void onSubscribe(Flow.Subscription subscription) { // 入参 订阅协议
                System.out.println("建立订阅关系第一次调用");
                this.subscription = subscription;
                this.subscription.request(1);
            }

            @Override
            public void onNext(String item) {
                System.out.println("接收数据：" + item);
                // 每次接收数据 都走onNext，发100接100
                this.subscription.request(1);
                //this.subscription.cancel();
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("onError：" + throwable.getMessage());
            }

            @Override
            public void onComplete() {
                System.out.println("结束：onComplete");
            }
        };
        // 建立订阅关系(会生成Subscription 契约)
        publisher.subscribe(subscriber);
        // 使用ExecutorService来在另一个线程中发布数据
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            publisher.submit("WebFlux");
            publisher.submit("Reactive Programming");
            // 完成后关闭发布者
            publisher.close();

        });
        //executor.shutdown();
    }
}
